import { RootState } from '@/types/store'
import { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'

// 泛型约束,约束stateName,必须是RootState的键
export function useInitialState<T extends keyof RootState>(
  action: () => void,
  stateName: T
) {
  const dispatch = useDispatch()
  const initState = useSelector((state: RootState) => state[stateName])

  useEffect(() => {
    dispatch(action())
  }, [dispatch, action])

  return initState
}
